﻿using BarcodeDelay.bean;
using BarcodeDelay.FrameDecoder;
using BarcodeDelay.logHelp;
using JTParcrelHelper.bean;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BarcodeDelay.business
{
    public class ZhongCaiHelperGen
    {
        private StreamWriter swb = null;
        FileStream bFile = null;
        ArrayList m_arListZCBarcodes = new ArrayList();
        public event Action zhongcaiEvent;
        string curUserToken = "";
        public bool isAutoUploadZC = false;
        public int curSpeed = 6;

        public int autoThreadCount = 20;
        public int totalExtThread = 0;
        public Hashtable htDelayType = new Hashtable();

        public Hashtable htThirdDelayType = new Hashtable();

        public Hashtable htNetWorkName = new Hashtable();
        ArrayList arListGlobalZCResult = new ArrayList();
        Hashtable htApplied = new Hashtable();
        public bool isNeedReLogin = false;
        public Hashtable htAllBarcodes = new Hashtable();

        public Hashtable htSiteNotEqualBarcodes = new Hashtable();
        private DateTime dtLastQueryJms = System.DateTime.Now;
        private static ZhongCaiHelperGen instance;
        public static ZhongCaiHelperGen Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new ZhongCaiHelperGen();
                }
                return instance;
            }
        }
        private Thread fThreadDep = null;
        public void BeginAnalyThread(ArrayList arListBarCodes, string token, bool isAutoZCTask,int speed)
        {
            try
            {
                isNeedReLogin = false;
                totalExtThread = 0;
                StoParams.Instance.sbZCAutoAdd.Clear();
                if(isAutoZCTask)
                {
                    parseAutoZhongCai(token, arListBarCodes);
                }
                else
                {
                    curSpeed = speed;
                    isAutoUploadZC = isAutoZCTask;
                    curUserToken = token;
                    initLog();
                    m_arListZCBarcodes.Clear();
                    if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                    {
                        fThreadDep.Abort();
                        System.Threading.Thread.Sleep(50);
                    }
                    if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                    {
                        while (fThreadDep.ThreadState != ThreadState.Aborted)
                        {
                            //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                            Thread.Sleep(100);
                        }
                    }


                    m_arListZCBarcodes = arListBarCodes;
                    fThreadDep = new Thread(new ParameterizedThreadStart(parseZhongCai));
                    fThreadDep.Start((object)arListBarCodes);

                    fThreadDep.IsBackground = true;
                }
                /*curSpeed = speed;
                isAutoUploadZC = isAutoZCTask;
                curUserToken = token;
                initLog();
                m_arListZCBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }


                m_arListZCBarcodes = arListBarCodes;
                fThreadDep = new Thread(new ParameterizedThreadStart(parseZhongCaiFast));
                fThreadDep.Start((object)arListBarCodes);

                fThreadDep.IsBackground = true;*/
                


            }
            catch (Exception ex)
            {

            }
        }



        public void BeginAnalyNormalZCThread(ArrayList arListBarCodes, string token)
        {
            try
            {
                isNeedReLogin = false;
                totalExtThread = 0;
                StoParams.Instance.sbZCAutoAdd.Clear();   
                curUserToken = token;
                initLog();
                m_arListZCBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }


                m_arListZCBarcodes = arListBarCodes;
                fThreadDep = new Thread(new ParameterizedThreadStart(parseZhongCai));
                fThreadDep.Start((object)arListBarCodes);

                fThreadDep.IsBackground = true;



            }
            catch (Exception ex)
            {

            }
        }




        public void BeginAnalyNongteZCThread(ArrayList arListBarCodes, string token)
        {
            try
            {
                isNeedReLogin = false;
                totalExtThread = 0;
                StoParams.Instance.sbZCAutoAdd.Clear();
                curUserToken = token;
                initLog();
                m_arListZCBarcodes.Clear();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    fThreadDep.Abort();
                    System.Threading.Thread.Sleep(50);
                }
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    while (fThreadDep.ThreadState != ThreadState.Aborted)
                    {
                        //当调用Abort方法后，如果thread线程的状态不为Aborted，主线程就一直在这里做循环，直到thread线程的状态变为Aborted为止
                        Thread.Sleep(100);
                    }
                }


                m_arListZCBarcodes = arListBarCodes;
                fThreadDep = new Thread(new ParameterizedThreadStart(parseZhongCai));
                fThreadDep.Start((object)arListBarCodes);

                fThreadDep.IsBackground = true;



            }
            catch (Exception ex)
            {

            }
        }





        private void handleZCBeanThread(object obj)
        {
            try
            {
                ZcBean zcBean = (ZcBean)obj;
                StoParams.Instance.resMsg = "";
                
                ArrayList arListAllGXTask = new ArrayList();
                string pickName = "";
                string orderSource = "";
                string curSiteToken = "";
                string customerName = "";
                /*if (!isAutoUploadZC)
                {
                    if (!UtilityHelp.Instance.resetToken(zcBean.wayBillNo, out pickName, out orderSource, out curSiteToken, out customerName))
                    {
                        if (curSiteToken == "")
                        {
                            StoParams.Instance.resMsg = " 发件网点 " + pickName + " 非我司单号  无法处理";
                            zhongcaiEvent.Invoke();
                            StoParams.Instance.htResWechat[zcBean.wayBillNo] = " 发件网点 " + pickName + " 非我司单号  无法处理";
                            arListGlobalZCResult.Add(zcBean.wayBillNo + " 发件网点 " + pickName + " 非我司单号  无法处理");
                            return;
                        }
                        StoParams.Instance.resMsg = " 发件网点 " + pickName + " 非我司单号  无法处理";
                        zhongcaiEvent.Invoke();
                        StoParams.Instance.htResWechat[zcBean.wayBillNo] = " 发件网点 " + pickName + " 非我司单号  无法处理";
                        arListGlobalZCResult.Add(zcBean.wayBillNo + " 发件网点 " + pickName + " 非我司单号  无法处理");
                        return;
                    }
                }*/

                //getCommonWay(zcBean);
               // getGoodsDetail(zcBean);
                //getSitesName(zcBean);
                //getSecondDelayType(zcBean);
                string outMsg = "";

                if (zcBean.isSuspend == "1")
                {
                    outMsg = " 结果: " + "网点异常";
                    arListGlobalZCResult.Add(zcBean.wayBillNo + outMsg);
                    StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                    zhongcaiEvent.Invoke();
                    return;
                }
                if (zcBean.goodsName == "")
                {
                    outMsg = " 结果: " + "未查到商品";
                    arListGlobalZCResult.Add(zcBean.wayBillNo + outMsg);
                    StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                    zhongcaiEvent.Invoke();
                    return;
                }
                if (zcBean.secondTypeId == "")
                {
                    outMsg = " 结果: " + "未查到延误类型";
                    arListGlobalZCResult.Add(zcBean.wayBillNo + outMsg);
                    StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                    zhongcaiEvent.Invoke();
                    return ;
                }

                addZhongCai(zcBean, out outMsg);
                totalExtThread++;
                if(outMsg.Contains("405"))
                {
                    isNeedReLogin = true;
                }

                if(outMsg.Contains("提交成功"))
                {
                    htApplied[zcBean.wayBillNo] = "";
                }
                else if (outMsg.Contains("已被申报"))
                {
                    htApplied[zcBean.wayBillNo] = "";
                }
                else if (outMsg.Contains("不予处理"))
                {
                    htApplied[zcBean.wayBillNo] = "";
                }
                StoParams.Instance.sbZCAutoAdd.AppendLine(System.DateTime.Now.ToString("hh:mm:ss.fff") + " " + zcBean.wayBillNo + " 提交仲裁结果 " + outMsg);
                if (totalExtThread >= StoParams.Instance.autoSelectedSpeed)
                {
                    StoParams.Instance.sbZCAutoAdd.AppendLine(System.DateTime.Now.ToString("hh:mm:ss.fff") + " 导入完成" + totalExtThread.ToString());
                }

                LogHelper.Instance.writeLog(zcBean.wayBillNo + " 提交仲裁结果 " + outMsg);
                arListGlobalZCResult.Add(zcBean.wayBillNo + " 提交仲裁结果 " + outMsg);
                string curMinute = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                /*if(totalExtThread>= autoThreadCount)
                {
                    string dir = System.Environment.CurrentDirectory;
                    string date = System.DateTime.Now.Date.ToShortDateString();
                    string path = StoParams.Instance.outputDir + "\\" + date + "批量仲裁结果.txt";
                    swb = new StreamWriter(path, true);
                    int sucessCount = 0;
                    foreach (string strLine in arListGlobalZCResult)
                    {
                        if (strLine.Contains("成功"))
                        {
                            sucessCount++;
                        }
                        swb.WriteLine(strLine);
                    }
                    swb.Close();
                    System.Windows.Forms.MessageBox.Show("批量仲裁提交完成，提交成功:" + sucessCount.ToString() + "条\r\n 详情见结果文件:" + path);
                }*/
                /*if (!htCurCount.ContainsKey(curMinute))
                {
                    htCurCount[curMinute] = 1;
                }
                else
                {
                    int curCout = Convert.ToInt32(htCurCount[curMinute].ToString()) + 1;
                    htCurCount[curMinute] = curCout;
                    if (curCout >= 3)
                    {

                        while (true)
                        {
                            if (System.DateTime.Now.ToString("yyyy-MM-dd HH:mm") != curMinute)
                            {
                                break;
                            }
                            Thread.Sleep(300);
                        }

                    }
                }*/

                if (outMsg.Contains("发生异常"))
                {
                    //htTotalFailResult[zcBean.wayBillNo] = zcBean;
                    //arListFailed.Add(zcBean.wayBillNo);
                    /*while (true)
                    {
                        if (System.DateTime.Now.ToString("yyyy-MM-dd HH:mm") != curMinute)
                        {
                            break;
                        }
                        Thread.Sleep(300);
                    }*/
                }
                else
                {
                    /*arListGlobalZCResult.Add(zcBean.wayBillNo + " 结果: " + outMsg);
                    StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                    zhongcaiEvent.Invoke();
                    FrameDecoderManager.Instance.lastSendRes = System.DateTime.Now;
                    Random rd2 = new Random();
                    int miniSecons = 3000;
                    int maxSeconds = 8000;
                    getMillSeconds(curSpeed, out miniSecons, out maxSeconds);
                    int sleepTime2 = rd2.Next(miniSecons, maxSeconds);
                    DateTime dtNow = System.DateTime.Now;
                    int second = dtNow.Second;
                    if (second > 50)
                    {
                        sleepTime2 = 60 * 1000 - second * 1000;
                    }*/
                    

                   
                    if (curSpeed < 100)
                    {
                        //System.Threading.Thread.Sleep(sleepTime2);
                    }
                }
            }
            catch(Exception ex)
            {

            }
        }
        public void parseZhongCaiFast(object arListBarcodes)
        {
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListZCResult = new ArrayList();
            try
            {
                int totalQueryCount = 0;
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                int sumQueryTime = 0;
                int avgQueryTime = 2;
                int intProcess = 0;
                string httpRes = "";

                StoParams.Instance.resMsg = "正在过滤掉非法网点和已申报过单号。。。";
                zhongcaiEvent.Invoke();

                string removeNoSite = removeNoSiteList((ArrayList)arListBarcodes);
                if (removeNoSite.Length > 10)
                {
                    arListZCResult.Add(removeNoSite);
                }
                ArrayList arListApplied = new ArrayList();
                string removeMsg = removeApplyedWaybill((ArrayList)arListBarcodes, arListApplied);
                if (removeMsg.Length > 10)
                {
                    arListZCResult.Add(removeMsg);
                }
                StoParams.Instance.resMsg = "过滤掉非法网点和已申报过单号成功";
                zhongcaiEvent.Invoke();
                ArrayList arListT = (ArrayList)arListBarcodes;
                /*if (arListT.Count > 0 && isAutoUploadZC)
                {
                    while (System.DateTime.Now.Hour != 6)
                    {
                        System.Threading.Thread.Sleep(20);
                        continue;
                    }
                }*/

                Hashtable htTotalFailResult = new Hashtable();
                ArrayList arListFailed = new ArrayList();
                Hashtable htCurCount = new Hashtable();

                DateTime dtLastZC = System.DateTime.Now.AddSeconds(-15);
                foreach (ZcBean zcBean in (ArrayList)arListBarcodes)
                {

                    Thread ftmpread = new Thread(new ParameterizedThreadStart(handleZCBeanThread));
                    ftmpread.Start((object)zcBean);

                    ftmpread.IsBackground = true;

                    
                    


                    //Thread.Sleep(1700);
                    //Thread.Sleep(300);


                }



                /*string dir = System.Environment.CurrentDirectory;
                string date = System.DateTime.Now.Date.ToShortDateString();
                string path = StoParams.Instance.outputDir + "\\" + date + "批量仲裁结果.txt";
                swb = new StreamWriter(path, true);
                int sucessCount = 0;
                foreach (string strLine in arListZCResult)
                {
                    if (strLine.Contains("成功"))
                    {
                        sucessCount++;
                    }
                    swb.WriteLine(strLine);
                }
                swb.Close();
                System.Windows.Forms.MessageBox.Show("批量仲裁提交完成，总计导入：" + totalQueryCount.ToString() + "条 提交成功:" + sucessCount.ToString() + "条\r\n 详情见结果文件:" + path);*/



            }
            catch (Exception ex)
            {


            }
            int tiot = queryServerResTime;



        }

        public void handleNotLanshouSite(object arListBarcodes)
        {
            try
            {
                StoParams.Instance.resMsg = "开始过滤揽收网点和发件网点不一致单号";
                zhongcaiEvent.Invoke();
                ArrayList arListT = (ArrayList)arListBarcodes;

                ArrayList arListNotSearched = new ArrayList();
                foreach (ZcBean zcBean in arListT)
                {
                    if (!htAllBarcodes.ContainsKey(zcBean.wayBillNo))
                    {
                        arListNotSearched.Add(zcBean);
                    }
                }

                foreach (ZcBean zcBean in arListNotSearched)
                {
                    string realPickName = "";
                    string pickName = "";
                    string orderSource = "";
                    string curSiteToken = "";
                    string customerName = "";
             
                    htAllBarcodes[zcBean.wayBillNo] = zcBean;
                    if (!UtilityHelp.Instance.resetToken(zcBean.wayBillNo, out pickName, out orderSource, out curSiteToken, out customerName, out realPickName))
                    {
                        StoParams.Instance.resMsg = zcBean.wayBillNo + " 揽收网点" + pickName + " 与实际网点 " + realPickName + "不一致";
                        zhongcaiEvent.Invoke();
                        htSiteNotEqualBarcodes[zcBean.wayBillNo] = zcBean;
                        continue;
                    }
                }
                ArrayList arListToDel = new ArrayList();
                foreach (DictionaryEntry de in htSiteNotEqualBarcodes)
                {
                    foreach (ZcBean zcBean in arListT)
                    {
                        if (zcBean.wayBillNo == de.Key.ToString())
                        {
                            arListToDel.Add(zcBean);
                        }
                    }

                }
                foreach (ZcBean zcCurrent in arListToDel)
                {
                    if (arListT.Contains(zcCurrent))
                    {
                        arListT.Remove(zcCurrent);
                    }
                }
            }
            catch (Exception ex)
            {

            }

        }
        public void parseZCAuto(object arListBarcodes)
        {
            try
            {

                m_arListZCBarcodes = (ArrayList)arListBarcodes;

               

                handleNotLanshouSite(m_arListZCBarcodes);

                StoParams.Instance.resMsg = "获取所有相关网点编号";
                zhongcaiEvent.Invoke();

                ArrayList arListDel = new ArrayList();
                for (int i = 0; i < m_arListZCBarcodes.Count; i++)
                {
                    ZcBean zcBean = (ZcBean)m_arListZCBarcodes[i];
                    if (htApplied.ContainsKey(zcBean.wayBillNo))
                    {
                        arListDel.Add(zcBean);
                    }
                }
                foreach(ZcBean zcBean in arListDel)
                {
                    if(m_arListZCBarcodes.Contains(zcBean))
                    {
                        m_arListZCBarcodes.Remove(zcBean);
                    }
                }
                for (int i = 0; i < m_arListZCBarcodes.Count; i++)
                {
                    ZcBean zcBean = (ZcBean)m_arListZCBarcodes[i];
                    getSitesName(zcBean);
                    getSecondDelayType(zcBean);
                }

               

                //StoParams.Instance.htResWechat.Clear();
                string resMsg = "";
                int totalDelays = 0;
                int queryServerResTime = 0;
                int priorBarCodeCount = 0;
                ArrayList arListZCResult = new ArrayList();
                try
                {
                    int totalQueryCount = 0;
                    ArrayList arListTmp = new ArrayList();
                    RoadInfo roadInfoGen = new bean.RoadInfo();
                    Hashtable htRoadMap = new Hashtable();
                    ArrayList arListBarCodes = new ArrayList();
                    arListBarCodes.Clear();
                    DateTime dtStart = System.DateTime.Now;
                    int sumQueryTime = 0;
                    int avgQueryTime = 2;
                    int intProcess = 0;
                    string httpRes = "";



                    string removeNoSite = removeNoSiteList((ArrayList)arListBarcodes);
                    if (removeNoSite.Length > 10)
                    {
                        arListZCResult.Add(removeNoSite);
                    }
                    /*string removeMsg = removeApplyedWaybill((ArrayList)arListBarcodes);
                    if (removeMsg.Length > 10)
                    {
                        arListZCResult.Add(removeMsg);
                    }*/
                    StoParams.Instance.resMsg = "过滤掉非法网点和已申报过单号成功";
                    zhongcaiEvent.Invoke();
                    ArrayList arListT = (ArrayList)arListBarcodes;
                    int hour = -1;
                    if(StoParams.Instance.autoMode.Contains("6点"))
                    {
                        hour = 6;
                    }
                    else if (StoParams.Instance.autoMode.Contains("12点"))
                    {
                        hour = 12;
                    }
                    if (arListT.Count > 0)
                    {
                        if(hour>0)
                        {
                            while (System.DateTime.Now.Hour != hour)
                            {
                                System.Threading.Thread.Sleep(20);
                                continue;
                            }
                        }
                        
                    }
                    int curMinuteCount = 0;
                    int curMinute = 0;
                    for (int i = 0; i < m_arListZCBarcodes.Count; i++)
                    {
                        curMinute = System.DateTime.Now.Minute;
                        curMinuteCount++;
                        ZcBean zcbean = (ZcBean)m_arListZCBarcodes[i];
                        Thread ftmpread = new Thread(new ParameterizedThreadStart(handleZCBeanThread));
                        ftmpread.Start((object)zcbean);
                        ftmpread.Priority = ThreadPriority.Highest;
                        ftmpread.IsBackground = true;
                        if (curMinuteCount > StoParams.Instance.autoSelectedSpeed)
                        {
                            if(isNeedReLogin)
                            {
                                break;
                            }
                            while(true)
                            {
                                System.Threading.Thread.Sleep(50);
                                int tmpMinute = System.DateTime.Now.Minute;
                                if(tmpMinute!= curMinute)
                                {
                                    curMinuteCount = 0;
                                    break;
                                }
                            }
                           
                        }
                        //ZcBean zcbean = (ZcBean)m_arListZCBarcodes[i];
                        //ThreadPool.QueueUserWorkItem(new WaitCallback(handleZCBeanThread), zcbean);

                    }








                }
                catch (Exception ex)
                {


                }
            }
            catch(Exception ex)
            {

            }
        }


        public void parseAutoZhongCai(string token, object arListBarcodes)
        {

            curUserToken = token;

            fThreadDep = new Thread(new ParameterizedThreadStart(parseZCAuto));
            fThreadDep.Start(arListBarcodes);

            fThreadDep.IsBackground = true;

           
           


        }



        public void parseZhongCai(object arListBarcodes)
        {
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListZCResult = new ArrayList();
            try
            {
                int totalQueryCount = 0;
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                int sumQueryTime = 0;
                int avgQueryTime = 2;
                int intProcess = 0;
                string httpRes = "";

                StoParams.Instance.resMsg = "正在过滤掉非法网点和已申报过单号。。。";
                zhongcaiEvent.Invoke();

                string removeNoSite = removeNoSiteList((ArrayList)arListBarcodes);
                if (removeNoSite.Length > 10)
                {
                    arListZCResult.Add(removeNoSite);
                }

                ArrayList arListTp = (ArrayList)arListBarcodes;
                ZcBean zcFirstBean = (ZcBean)arListTp[0]; ;
                ArrayList arListApplied = new ArrayList();
                string removeMsg = removeApplyedWaybill((ArrayList)arListBarcodes, arListApplied);
                if (removeMsg.Length > 10)
                {
                    arListZCResult.Add(removeMsg);
                }
                StoParams.Instance.resMsg = "过滤掉非法网点和已申报过单号成功";
                zhongcaiEvent.Invoke();
                ArrayList arListT = (ArrayList)arListBarcodes;


                if(arListT.Count>0&& StoParams.Instance.normalBeginExcuteTime!="")
                {
                    DateTime dtExcute = Convert.ToDateTime(StoParams.Instance.normalBeginExcuteTime);
                    if(System.DateTime.Now.Hour != dtExcute.Hour)
                    {
                        while (System.DateTime.Now.Hour != dtExcute.Hour)
                        {
                            if (System.DateTime.Now.Minute == dtExcute.Minute && System.DateTime.Now.Hour == dtExcute.Hour)
                            {
                                break;
                            }
                            TimeSpan ts = System.DateTime.Now - dtLastQueryJms;
                            if (ts.TotalMinutes > 3)
                            {
                                ArrayList arListAllGXTask3 = new ArrayList();
                                string httpRes3 = "";
                                ArrayList arListRoadMap3 = JTDelayHelper.Instance.getRoadMap(zcFirstBean.wayBillNo, out httpRes3, arListAllGXTask3);
                                dtLastQueryJms = System.DateTime.Now;
                            }
                            System.Threading.Thread.Sleep(200);
                            continue;
                        }
                    }
                    else
                    {
                        while (System.DateTime.Now.Minute != dtExcute.Minute)
                        {
                            if (System.DateTime.Now.Minute == dtExcute.Minute && System.DateTime.Now.Hour == dtExcute.Hour)
                            {
                                break;
                            }
                            TimeSpan ts = System.DateTime.Now - dtLastQueryJms;
                            if (ts.TotalMinutes > 3)
                            {
                                ArrayList arListAllGXTask3 = new ArrayList();
                                string httpRes3 = "";
                                ArrayList arListRoadMap3 = JTDelayHelper.Instance.getRoadMap(zcFirstBean.wayBillNo, out httpRes3, arListAllGXTask3);
                                dtLastQueryJms = System.DateTime.Now;
                            }
                            System.Threading.Thread.Sleep(200);
                            continue;
                        }
                    }
                    
                }

                Hashtable htTotalFailResult = new Hashtable();
                ArrayList arListFailed = new ArrayList();
                Hashtable htCurCount = new Hashtable();

                DateTime dtLastZC = System.DateTime.Now.AddSeconds(-15);
                bool isCurBarcodeValid = true;
                ArrayList arListAppliedTmp = new ArrayList();
                int curIndex = 0;
                ArrayList art = (ArrayList)arListBarcodes;
                int arTotal = art.Count;
                foreach (ZcBean zcBean  in (ArrayList)arListBarcodes)
                {
                   
                    totalQueryCount++;
                    StoParams.Instance.resMsg = "";
                    intProcess++;
                    curIndex++;
                    if (arListAppliedTmp.Contains(zcBean.wayBillNo))
                    {
                        continue;
                    }
                    
                    ArrayList arListAllGXTask = new ArrayList();
                    string pickName = "";
                    string orderSource = "";
                    string curSiteToken = "";
                    string customerName = "";
                    string realPickName = "";
                    if (!isAutoUploadZC)
                    {
                        if (!UtilityHelp.Instance.resetToken(zcBean.wayBillNo, out pickName, out orderSource, out curSiteToken,out customerName,out realPickName))
                        {
                            if (curSiteToken == "")
                            {
                                StoParams.Instance.resMsg = " 发件网点 " + pickName + " 非我司单号  无法处理";
                                zhongcaiEvent.Invoke();
                                StoParams.Instance.htResWechat[zcBean.wayBillNo] = " 发件网点 " + pickName + " 非我司单号  无法处理";
                                arListZCResult.Add(zcBean.wayBillNo + " 发件网点 " + pickName + " 非我司单号  无法处理");
                                continue;
                            }
                            StoParams.Instance.resMsg = " 发件网点 " + pickName + " 非我司单号或者与实际揽收网点"+realPickName+"  不一致无法处理";
                            zhongcaiEvent.Invoke();
                            StoParams.Instance.htResWechat[zcBean.wayBillNo] = " 发件网点 " + pickName + " 非我司单号  无法处理";
                            arListZCResult.Add(zcBean.wayBillNo + " 发件网点 " + pickName + " 非我司单号或者与实际揽收网点" + realPickName + "  不一致无法处理");
                            continue;
                        }
                    }
                    
                    //getCommonWay(zcBean);
                    //getGoodsDetail(zcBean);
                    getSitesName(zcBean);
                    getSecondDelayType(zcBean);
                    string outMsg = "";

                    if (zcBean.isSuspend == "1")
                    {
                        outMsg = " 结果: " + "网点异常";
                        arListZCResult.Add(zcBean.wayBillNo + outMsg);
                        StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                        zhongcaiEvent.Invoke();
                        continue;
                    }
                    if (zcBean.goodsName=="")
                    {
                        outMsg = " 结果: " + "未查到商品";
                        arListZCResult.Add(zcBean.wayBillNo + outMsg);
                        StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                        zhongcaiEvent.Invoke();
                        continue;
                    }
                    if (zcBean.secondTypeId == "")
                    {
                        outMsg = " 结果: " + "未查到延误类型";
                        arListZCResult.Add(zcBean.wayBillNo + outMsg);
                        StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                        zhongcaiEvent.Invoke();
                        continue;
                    }
                    TimeSpan tsCur = System.DateTime.Now - dtLastZC;
                    int miniSleep = 0;
                    int maxSleep = 0;
                    getSecondsBySpped(StoParams.Instance.miniSpeed, out miniSleep);
                    getSecondsBySpped(StoParams.Instance.maxSpeed, out maxSleep);
                    Random rdSl = new Random();
 
                    int sleepTimeMandom = rdSl.Next(maxSleep,miniSleep );

                    int randomSeconds = sleepTimeMandom;
                    //while (tsCur.TotalSeconds<15)
                    if(randomSeconds<=15)
                    {
                        randomSeconds = 16;
                    }
                    arListAppliedTmp.Clear();
                    while (tsCur.TotalSeconds < randomSeconds)
                    {
                        JArray wayBills = new JArray();

                        for(int curRow=curIndex; curRow< arTotal; curRow++)
                        {
                            ZcBean zc = art[curRow] as ZcBean;
                            wayBills.Add(zc.wayBillNo);
                            break;
                        }                     

                        arListAppliedTmp = getcurPageApplyed(wayBills);
                        if(arListAppliedTmp.Count>0)
                        {
                            LogHelper.Instance.writeLog(zcBean.wayBillNo + " 已被别人提交 ");
                            break;
                        }

                        Thread.Sleep(100);
                        tsCur = System.DateTime.Now - dtLastZC;
                    }
                    if (arListAppliedTmp.Count > 0)
                    {
                        continue;
                    }

                    addZhongCai(zcBean, out outMsg);
                    dtLastZC = System.DateTime.Now;
                    LogHelper.Instance.writeLog(zcBean.wayBillNo+" 提交仲裁结果 " + outMsg);
                    string curMinute=System.DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                    /*if (!htCurCount.ContainsKey(curMinute))
                    {
                        htCurCount[curMinute] = 1;
                    }
                    else
                    {
                        int curCout = Convert.ToInt32(htCurCount[curMinute].ToString()) + 1;
                        htCurCount[curMinute] = curCout;
                        if (curCout >= 3)
                        {

                            while (true)
                            {
                                if (System.DateTime.Now.ToString("yyyy-MM-dd HH:mm") != curMinute)
                                {
                                    break;
                                }
                                Thread.Sleep(300);
                            }

                        }
                    }*/

                    if (outMsg.Contains("发生异常"))
                    {
                        htTotalFailResult[zcBean.wayBillNo] = zcBean;
                        arListFailed.Add(zcBean.wayBillNo);
                        /*while (true)
                        {
                            if (System.DateTime.Now.ToString("yyyy-MM-dd HH:mm") != curMinute)
                            {
                                break;
                            }
                            Thread.Sleep(300);
                        }*/
                    }
                    else
                    {
                        arListZCResult.Add(zcBean.wayBillNo + " 结果: " + outMsg);
                        StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                        zhongcaiEvent.Invoke();
                        FrameDecoderManager.Instance.lastSendRes = System.DateTime.Now;
                        Random rd2 = new Random();
                        int miniSecons = 3000;
                        int maxSeconds = 8000;
                        getMillSeconds(curSpeed, out miniSecons, out maxSeconds);
                        int sleepTime2 = rd2.Next(miniSecons, maxSeconds);
                        DateTime dtNow = System.DateTime.Now;
                        int second = dtNow.Second;
                        if(second>50)
                        {
                            sleepTime2 = 60 * 1000 - second * 1000;
                        }
                        System.Threading.Thread.Sleep(1000);
                        //int sleepTime2 = rd2.Next(8000, 12000);
                        //System.Threading.Thread.Sleep(sleepTime2);
                        //int sleepTime2 = rd2.Next(1500, 3500);
                        if (isAutoUploadZC)
                        {
                            continue;
                        }

                        string newMinute = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                        if(!htCurCount.ContainsKey(newMinute))
                        {
                            continue;
                        }
                        if (curSpeed < 100)
                        {
                            //System.Threading.Thread.Sleep(sleepTime2);
                        }
                    }
                    
                    
                    //Thread.Sleep(1700);
                    //Thread.Sleep(300);


                }

                foreach(string strWaybill in arListFailed)
                {
                    System.Threading.Thread.Sleep(15000);
                    if(htTotalFailResult.ContainsKey(strWaybill))
                    {
                        ZcBean zcBean = htTotalFailResult[strWaybill] as ZcBean;
                        getCommonWay(zcBean);
                        getGoodsDetail(zcBean);
                        getSitesName(zcBean);
                        getSecondDelayType(zcBean);
                        string outMsg = "";

                        if (zcBean.isSuspend == "1")
                        {
                            outMsg = " 结果: " + "网点异常";
                            arListZCResult.Add(zcBean.wayBillNo + outMsg);
                            StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                            zhongcaiEvent.Invoke();
                            continue;
                        }
                        if (zcBean.goodsName == "")
                        {
                            outMsg = " 结果: " + "未查到商品";
                            arListZCResult.Add(zcBean.wayBillNo + outMsg);
                            StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                            zhongcaiEvent.Invoke();
                            continue;
                        }
                        if (zcBean.secondTypeId == "")
                        {
                            outMsg = " 结果: " + "未查到延误类型";
                            arListZCResult.Add(zcBean.wayBillNo + outMsg);
                            StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                            zhongcaiEvent.Invoke();
                            continue;
                        }

                        addZhongCai(zcBean, out outMsg);
                        
                        arListZCResult.Add(zcBean.wayBillNo + " 结果: " + outMsg);
                    }
                    

                }

                string dir = System.Environment.CurrentDirectory;
                string date = System.DateTime.Now.Date.ToShortDateString();
                string path = StoParams.Instance.outputDir + "\\" + date + "批量仲裁结果.txt";
                swb = new StreamWriter(path, true);
                int sucessCount = 0;
                foreach (string strLine in arListZCResult)
                {
                    if(strLine.Contains("成功"))
                    {
                        sucessCount++;
                    }
                    swb.WriteLine(strLine);
                }
                swb.Close();
                System.Windows.Forms.MessageBox.Show("批量仲裁提交完成，总计导入："+ totalQueryCount.ToString()+"条 提交成功:"+ sucessCount.ToString()+"条\r\n 详情见结果文件:"+ path);



            }
            catch (Exception ex)
            {
                

            }
            int tiot = queryServerResTime;
           


        }


        public void getSecondsBySpped(int curSpeed,  out int maxSeconds)
        {
            maxSeconds = 15;
            if (curSpeed==0)
            {
                return;
            }
            
            int curMill = (60) / curSpeed;
            maxSeconds = curMill;

        }


        public void getMillSeconds(int curSpeed, out int minSeconds,out int maxSeconds)
        {
            minSeconds = 6000;
            maxSeconds = 10000;
            int curMill = (60 * 1000) / curSpeed;
            maxSeconds = curMill;
            minSeconds = curMill - 2000;
            if(minSeconds<0)
            {
                minSeconds = 100;
            }

        }

        private bool addZhongCai(ZcBean zcBean, out string msg)
        {
            msg = "";
            bool res = false;
            try
            {
               
                string strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/arbitration/add";
                if(StoParams.Instance.isRabbitWin)
                {
                    strUrl = "https://wdgw.jtexpress.com.cn/servicequality/arbitration/add";
                }
                JObject jObj = new JObject();
                JArray jarry = new JArray();               
               
                string signStieCode = "";
                int receiveNetworkId = 0;                
                string routerName = "arbitrationApply";
                jObj = new JObject();
                JObject complaintNetworks = zcBean.jObjNetWrokSite;
                complaintNetworks["children"] = new JArray();
                complaintNetworks["label"] = zcBean.dutySite+"|"+ zcBean.dutyCode;
                JArray arrayObjNetWorks = new JArray();
                arrayObjNetWorks.Add(complaintNetworks);

                jObj["isVip"] = Convert.ToInt32(zcBean.isVip);
                jObj["firstTypeId"] = zcBean.firstTypeId;
                jObj["secondTypeId"] = zcBean.secondTypeId;
                jObj["exceptionDesc"] = zcBean.errorMsg;
                jObj["isValueProve"] = 0;
                jObj["selectNetwork"] = new JArray();
                if(!zcBean.firstType.Contains("私自退"))
                {
                    jObj["delayDay"] = zcBean.delayDays;
                }
                
                jObj["network"] = StoParams.Instance.register_site;
                jObj["goodsName"] = zcBean.goodsName;
                /*jObj["goodsTypeId"] = Convert.ToInt32(zcBean.goodsTypeId);
                jObj["goodsTypeName"] = zcBean.goodsTypeName;
                jObj["goodsTypeCode"] = zcBean.goodsTypeCode;*/

                jObj["goodsTypeId"] = 60;
                jObj["goodsTypeName"] = "其他";
                jObj["goodsTypeCode"] = "bm000006";


                jObj["goodsValue"] = zcBean.goodsValue;
                jObj["firstTypeCode"] = zcBean.firstTypeCode;
                jObj["secondTypeCode"] = zcBean.secondTypeCode;
                jObj["waybillNo"] = zcBean.wayBillNo;
                jObj["complaintNetwork1"] = zcBean.dutySite;
                jObj["isAllPod"] =2;
                jObj["paths"] = new JArray();
                jObj["thirdRemark"] = zcBean.thirdType;
                jObj["countryId"] = "1";
                jObj["complaintNetworks"] = arrayObjNetWorks;
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);

                HttpClient.HttpUtil httpInstance = new HttpClient.HttpUtil();
                string resMsg = httpInstance.PostCommonByToken(strUrl, postData, routerName, curUserToken);
                //string resMsg = HttpClient.HttpUtil.Instance.PostCommonByToken(strUrl, postData, routerName, curUserToken);
                if (!resMsg.Contains("请求成功"))
                {
                    try
                    {
                        JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                        JToken msgToke = jsonObjRes["msg"];

                        msg = zcBean.wayBillNo + "提交失败:" + msgToke.ToString();
                    }
                    catch(Exception e)
                    {
                        msg = zcBean.wayBillNo + "提交失败:" + resMsg.ToString();
                    }
                    
                    return false;
                }
                else
                {
                    msg = "提交成功";
                   
                    return true;
                }
               

            }
            catch (Exception ex)
            {
                msg = zcBean.wayBillNo+" 提交失败:发生异常" + ex.ToString();
                return false;
            }



            return res;
        }


        private void getSitesName(ZcBean zcBean)
        {
            try
            {
                if(htNetWorkName.ContainsKey(zcBean.dutySite))
                {
                    NetWorkBean netWorkBean = htNetWorkName[zcBean.dutySite] as NetWorkBean;
                    zcBean.jObjNetWrokSite = netWorkBean.jObjNetWrokSite;
                    zcBean.dutyCode = netWorkBean.dutyCode;
                    zcBean.dutyId = netWorkBean.dutyId;
                    zcBean.typeId = netWorkBean.typeId;
                    zcBean.openingTime = netWorkBean.openingTime;
                    zcBean.isSuspend = netWorkBean.isSuspend;
                    zcBean.leavingTime = netWorkBean.leavingTime;
                    zcBean.openingType = netWorkBean.openingType;
                    zcBean.functionTypeId = netWorkBean.functionTypeId;
                    zcBean.newOpen = netWorkBean.newOpen;                   

                    return;
                }

                string strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/network/byName?current=1&size=10&name="+ zcBean.dutySite + "&queryLevel=3";

                if(StoParams.Instance.isRabbitWin)
                {
                    strUrl = "https://wdgw.jtexpress.com.cn/servicequality/network/byName?current=1&size=10&name=" + zcBean.dutySite + "&queryLevel=3";
                }
                JObject jObj = new JObject();
                JArray jarry = new JArray();
                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "arbitrationApply");
                if (!resMsg.Contains("请求成功"))
                {
                    return;
                }
                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JObject jsonObjData = (JObject)jsonObjRes["data"];
                JArray records = (JArray)jsonObjData["records"];
                if (records.Count == 0)
                {
                    return;
                }
                string signStieCode = "";
                int receiveNetworkId = 0;
                for (int i = 0; i < records.Count; i++)
                {
                    JObject json = (JObject)records[i];
                    JToken code = json["code"];
                    JToken name = json["name"];
                    JToken id = json["id"];
                    if (code != null)
                    {
                        if (name.ToString() == zcBean.dutySite)
                        {
                            NetWorkBean netWorkBean = new NetWorkBean();
                            zcBean.jObjNetWrokSite = json;
                            zcBean.dutyCode = code.ToString();
                            zcBean.dutyId = id.ToString();
                            zcBean.typeId= json["typeId"].ToString();

                            netWorkBean.jObjNetWrokSite = json;
                            netWorkBean.dutyCode= code.ToString();
                            netWorkBean.dutyId= id.ToString();
                            netWorkBean.typeId= json["typeId"].ToString();

                            JToken openingTime = json["openingTime"];
                            if(openingTime!=null)
                            {
                                zcBean.openingTime = openingTime.ToString();
                                netWorkBean.openingTime= openingTime.ToString();
                            }
                            JToken isSuspend = json["isSuspend"];
                            if (isSuspend != null)
                            {
                                zcBean.isSuspend = isSuspend.ToString();
                                netWorkBean.isSuspend= isSuspend.ToString();
                            }

                            JToken leavingTime = json["leavingTime"];
                            if (leavingTime != null)
                            {
                                zcBean.leavingTime = leavingTime.ToString();
                                netWorkBean.leavingTime= leavingTime.ToString();
                            }

                            JToken openingType = json["openingType"];
                            if (openingType != null)
                            {
                                zcBean.openingType = openingType.ToString();
                                netWorkBean.openingType= openingType.ToString();
                            }
                            JToken functionTypeId = json["functionTypeId"];
                            if (functionTypeId != null)
                            {
                                zcBean.functionTypeId = functionTypeId.ToString();
                                netWorkBean.functionTypeId = functionTypeId.ToString();
                            }

                            JToken newOpen = json["newOpen"];
                            if (newOpen != null)
                            {
                                zcBean.newOpen = Convert.ToBoolean(newOpen);
                                netWorkBean.newOpen = Convert.ToBoolean(newOpen);
                            }
                            htNetWorkName[zcBean.dutySite] = netWorkBean;

                            break;
                        }
                    }
                }


            }
            catch (Exception ex)
            {

            }
        }


        private void getSecondDelayType(ZcBean zcBean)
        {
            try
            {
                string firstId = "128398660034629685";
                zcBean.firstTypeCode = "01";
                if (zcBean.firstType.Contains("私自退"))
                {
                    firstId = "516806902743580701";
                    zcBean.firstTypeCode = "18";
                }
               
                if (htDelayType.ContainsKey(zcBean.secondType))
                {
                    DelayTypeBean delayTypeBean = htDelayType[zcBean.secondType] as DelayTypeBean;
                    zcBean.firstTypeId = firstId;
                    zcBean.secondTypeId = delayTypeBean.secondTypeId;
                    zcBean.secondTypeCode = delayTypeBean.secondTypeCode;
                    return;
                }
                string strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/arbitrationType/list/second?isEnable=1&firstId="+ firstId;
                if(StoParams.Instance.isRabbitWin)
                {
                    strUrl = "https://wdgw.jtexpress.com.cn/servicequality/arbitrationType/list/second?isEnable=1&firstId=" + firstId;
                }
                JObject jObj = new JObject();
                JArray jarry = new JArray();

                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "arbitrationApply");
                if (!resMsg.Contains("请求成功"))
                {
                    return;
                }
                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JArray jsonObjData = (JArray)jsonObjRes["data"];
                bool isContainNT = false;
                for(int i=0;i< jsonObjData.Count;i++)
                {
                    JObject jobj = (JObject)jsonObjData[i];
                    if(jobj["name"].ToString()==zcBean.secondType)
                    {
                        zcBean.firstTypeId = jobj["firstId"].ToString();
                        zcBean.secondTypeId = jobj["id"].ToString();
                        zcBean.secondTypeCode = jobj["code"].ToString();                       
                        
                    }
                    if(!htDelayType.ContainsKey(jobj["name"].ToString()))
                    {
                        DelayTypeBean delayTypeBean = new DelayTypeBean();
                        delayTypeBean.secondTypeId= jobj["id"].ToString();
                        delayTypeBean.secondTypeCode = jobj["code"].ToString();
                        htDelayType[jobj["name"].ToString()] = delayTypeBean;
                    }
                }


            }
            catch (Exception ex)
            {

            }
        }



        private void getThirdDelayType(ZcBean zcBean)
        {
            try
            {
                string firstId = "128398660034629685";
                string firstTypeCode = "01";
                string secondType = "319013827117056015";
                string secodeCode = "0113";

                if (htThirdDelayType.ContainsKey(zcBean.thirdType))
                {
                    zcBean.isFindThird = true;
                    return;
                }
                string strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/arbitrationType/getThirdTypeRemarkBySecondId?secondId=319013827117056015";
                if(StoParams.Instance.isRabbitWin)
                {
                    strUrl = "https://wdgw.jtexpress.com.cn/servicequality/arbitrationType/getThirdTypeRemarkBySecondId?secondId=319013827117056015";
                }
                JObject jObj = new JObject();
                JArray jarry = new JArray();

                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "arbitrationApply");
                if (!resMsg.Contains("请求成功"))
                {
                    return;
                }
                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JArray jsonObjData = (JArray)jsonObjRes["data"];
                bool isContainNT = false;
                for (int i = 0; i < jsonObjData.Count; i++)
                {
                    JObject jobj = (JObject)jsonObjData[i];
                    if (jobj["name"].ToString() == zcBean.thirdType)
                    {
                        zcBean.isFindThird = true;

                    }
                    if (!htThirdDelayType.ContainsKey(jobj["name"].ToString()))
                    {
                        DelayTypeBean delayTypeBean = new DelayTypeBean();
                        htThirdDelayType[jobj["name"].ToString()] = delayTypeBean;
                    }
                }


            }
            catch (Exception ex)
            {

            }
        }

        private void getGoodsDetail(ZcBean zcBean)
        {
            try
            {
                string strUrl = "https://jmsgw.jtexpress.com.cn/networkmanagement/omsWaybill/detail?waybillNo=" + zcBean.wayBillNo;
                JObject jObj = new JObject();
                JArray jarry = new JArray();

                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "arbitrationApply");
                if (!resMsg.Contains("请求成功"))
                {
                    return;
                }
                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JObject jsonObjData = (JObject)jsonObjRes["data"];
                string goodsName = jsonObjData["goodsName"].ToString();
                string goodsTypeId = jsonObjData["goodsTypeId"].ToString();
                string goodsTypeCode = jsonObjData["goodsTypeCode"].ToString();
                string goodsTypeName = jsonObjData["goodsTypeName"].ToString();
                //zcBean.goodsName = goodsName;
                zcBean.goodsTypeName = goodsTypeName;
                zcBean.goodsTypeCode = goodsTypeCode;
                zcBean.goodsTypeId = goodsTypeId;
                


            }
            catch(Exception ex)
            {

            }
        }





        private void getCommonWay(ZcBean zcBean)
        {
            try
            {
                string strUrl = "https://jmsgw.jtexpress.com.cn/sqsthird/thirdService/waybill/commonWaybillListByWaybillNos?waybillNos=" + zcBean.wayBillNo;
                JObject jObj = new JObject();
                JArray jarry = new JArray();

                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.QueryCommon(strUrl, postData, "GET", "arbitrationApply");
                if (!resMsg.Contains("请求成功"))
                {
                    return;
                }
                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JArray jsonObjDataArr = (JArray)jsonObjRes["data"];
                if(jsonObjDataArr.Count>0)
                {
                    JObject jsonObjCurRes = (JObject)jsonObjDataArr[0];
                    string isVip = jsonObjCurRes["isVip"].ToString();
                    if(isVip.Length>0)
                    {
                        zcBean.isVip = isVip;
                    }
                    else
                    {
                        int a = 2;
                    }
                }              

            }
            catch (Exception ex)
            {

            }
        }



        private ArrayList getcurPageApplyed(JArray waybills)
        {
            ArrayList arListAppliedWaybills = new ArrayList();
            try
            {
                string strUrl = "https://jmsgw.jtexpress.com.cn/servicequality/arbitration/list?size=100&current=1";
                if(StoParams.Instance.isRabbitWin)
                {
                    strUrl = "https://wdgw.jtexpress.com.cn/servicequality/arbitration/list?size=100&current=1";
                }
                JObject jObj = new JObject();

                jObj["createNetworkId"] = Convert.ToInt64(StoParams.Instance.register_networkId);
                jObj["countryId"] = "1";
                jObj["dateType"] = 0;
                jObj["startDate"] = System.DateTime.Now.ToShortDateString()+" 23:59:59";
                jObj["endDate"] = System.DateTime.Now.ToShortDateString() + " 23:59:59";
                jObj["firstId"] = "";
                jObj["secondId"] = "";
                jObj["timeout"] = 25000;
                jObj["type"] = 1;
                jObj["waybillNos"] = waybills;

                string postData = Newtonsoft.Json.JsonConvert.SerializeObject(jObj);
                string resMsg = HttpClient.HttpUtil.Instance.PostCommonByToken(strUrl, postData,  "arbitrationMyApply",curUserToken);
                if (!resMsg.Contains("请求成功"))
                {
                    return arListAppliedWaybills;
                }

                JObject jsonObjRes = (JObject)JsonConvert.DeserializeObject(resMsg);
                JObject jsonObjData = (JObject)jsonObjRes["data"];
                JArray records = (JArray)jsonObjData["records"];

                for (int i = 0; i < records.Count; i++)
                {
                    JObject json = (JObject)records[i];
                    JToken waybillNo = json["waybillNo"];
                    arListAppliedWaybills.Add(waybillNo.ToString());
                }
            }
            catch (Exception ex)
            {

            }
            return arListAppliedWaybills;
        }


        public string removeApplyedWaybill(ArrayList arListZcBean,ArrayList arListAppliedWaybill)
        {
            string res = "";
            try
            {
                Hashtable htWayBillZcBean = new Hashtable();
                ArrayList arListTotal = new ArrayList();
                ArrayList arListTmp = new ArrayList();
                foreach (ZcBean zcBean in arListZcBean)
                {
                    htWayBillZcBean[zcBean.wayBillNo] = zcBean;
                    arListTmp.Add(zcBean);
                    if (arListTmp.Count >= 100)
                    {
                        arListTotal.Add(arListTmp.Clone());
                        arListTmp.Clear();
                    }
                }
                if (arListTmp.Count > 0)
                {
                    arListTotal.Add(arListTmp.Clone());
                }
                foreach (ArrayList arListCurrent in arListTotal)
                {
                    JArray wayBills = new JArray();
                    foreach (ZcBean zc in arListCurrent)
                    {
                        wayBills.Add(zc.wayBillNo);
                    }

                    ArrayList arListApplied = getcurPageApplyed(wayBills);
                    foreach (string strApplied in arListApplied)
                    {
                        arListAppliedWaybill.Add(strApplied);
                        if (htWayBillZcBean.ContainsKey(strApplied))
                        {
                            ZcBean zcCurrent = htWayBillZcBean[strApplied] as ZcBean;
                            if (arListZcBean.Contains(zcCurrent))
                            {
                                arListZcBean.Remove(zcCurrent);
                                res = res + zcCurrent.wayBillNo + " ";
                            }
                        }

                    }
                }
                if (res.Length > 10)
                {
                    res = "去掉已仲裁单号 " + res;
                    StoParams.Instance.resMsg = res;
                    zhongcaiEvent.Invoke();
                }


            }
            catch (Exception ex)
            {

            }
            return res;
        }

        public bool isDutySiteInRoad(ZcBean zcBean,ArrayList arListRoadMap)
        {
            bool isInRoad = false;
            try
            {
                foreach(RoadBean roadBean in arListRoadMap)
                {
                    if(roadBean.scanNetworkName==zcBean.dutySite)
                    {
                        isInRoad = true;
                        return isInRoad;
                    }
                }
            }
            catch(Exception ex)
            {

            }
            return isInRoad;
        }

        public string removeNoSiteList(ArrayList arListZcBean)
        {
            string res = "";
            try
            {
                Hashtable htWayBillZcBean = new Hashtable();
                ArrayList arListTotal = new ArrayList();
                ArrayList arListTmp = new ArrayList();
                foreach(ZcBean zcBean in arListZcBean)
                {
                    htWayBillZcBean[zcBean.wayBillNo] = zcBean;
                    arListTmp.Add(zcBean);
                    if(arListTmp.Count>=100)
                    {
                        arListTotal.Add(arListTmp.Clone());
                        arListTmp.Clear();
                    }
                }
                if(arListTmp.Count>0)
                {
                    arListTotal.Add(arListTmp.Clone());
                }
                ArrayList arListWrong = new ArrayList();
                foreach (ArrayList arListCurrent in arListTotal)
                {
                    JArray wayBills = new JArray();
                    foreach(ZcBean zc in arListCurrent)
                    {
                        ArrayList arListAllGXTask3 = new ArrayList();
                        string httpRes3 = "";
                        ArrayList arListRoadMap3 = JTDelayHelper.Instance.getRoadMap(zc.wayBillNo, out httpRes3, arListAllGXTask3);
                        if(!isDutySiteInRoad(zc, arListRoadMap3))
                        {
                            arListWrong.Add(zc.wayBillNo);
                        }
                    }
                    
                   
                    foreach(string waybillNo in arListWrong)
                    {
                        if (htWayBillZcBean.ContainsKey(waybillNo))
                        {
                            ZcBean zcCurrent = htWayBillZcBean[waybillNo] as ZcBean;
                            if(arListZcBean.Contains(zcCurrent))
                            {
                                arListZcBean.Remove(zcCurrent);
                                res = res + zcCurrent.wayBillNo + " ";
                            }
                        }

                    }
                }
                if(res.Length>10)
                {
                    res = "去掉不在轨迹里的网点的单号 " + res;
                    StoParams.Instance.resMsg = res;
                    zhongcaiEvent.Invoke();
                }
                

            }
            catch(Exception ex)
            {

            }
            return res;
        }

        public void stopThread()
        {
            try
            {
                ArrayList arListT = new ArrayList();
                ResultBean resultBean = new ResultBean();
                if (fThreadDep != null && (fThreadDep.ThreadState == ThreadState.Running || fThreadDep.ThreadState == ThreadState.Background))
                {
                    /*if (totalQueryCount > 0)
                    {
                        resultBean.countTime = totalQueryCount;

                        updateQueryCount(resultBean);
                    }*/
                    fThreadDep.Abort();
                    if (swb != null)
                    {
                        swb.Close();
                    }

                }

    
            }
            catch (Exception ex)
            {

            }
        }



        public void parseNongteZhongCai(object arListBarcodes)
        {
            //StoParams.Instance.htResWechat.Clear();
            string resMsg = "";
            int totalDelays = 0;
            int queryServerResTime = 0;
            int priorBarCodeCount = 0;
            ArrayList arListZCResult = new ArrayList();
            try
            {
                int totalQueryCount = 0;
                ArrayList arListTmp = new ArrayList();
                RoadInfo roadInfoGen = new bean.RoadInfo();
                Hashtable htRoadMap = new Hashtable();
                ArrayList arListBarCodes = new ArrayList();
                arListBarCodes.Clear();
                DateTime dtStart = System.DateTime.Now;
                int sumQueryTime = 0;
                int avgQueryTime = 2;
                int intProcess = 0;
                string httpRes = "";

                StoParams.Instance.resMsg = "正在过滤掉非法网点和已申报过单号。。。";
                zhongcaiEvent.Invoke();

                string removeNoSite = removeNoSiteList((ArrayList)arListBarcodes);
                if (removeNoSite.Length > 10)
                {
                    arListZCResult.Add(removeNoSite);
                }

                ArrayList arListTp = (ArrayList)arListBarcodes;
                ZcBean zcFirstBean = (ZcBean)arListTp[0]; ;
                ArrayList arListApplied = new ArrayList();
                string removeMsg = removeApplyedWaybill((ArrayList)arListBarcodes, arListApplied);
                if (removeMsg.Length > 10)
                {
                    arListZCResult.Add(removeMsg);
                }
                StoParams.Instance.resMsg = "过滤掉非法网点和已申报过单号成功";
                zhongcaiEvent.Invoke();
                ArrayList arListT = (ArrayList)arListBarcodes;


                if (arListT.Count > 0 && StoParams.Instance.normalBeginExcuteTime != "")
                {
                    DateTime dtExcute = Convert.ToDateTime(StoParams.Instance.normalBeginExcuteTime);
                    if (System.DateTime.Now.Hour != dtExcute.Hour)
                    {
                        while (System.DateTime.Now.Hour != dtExcute.Hour)
                        {
                            if (System.DateTime.Now.Minute == dtExcute.Minute && System.DateTime.Now.Hour == dtExcute.Hour)
                            {
                                break;
                            }
                            TimeSpan ts = System.DateTime.Now - dtLastQueryJms;
                            if (ts.TotalMinutes > 3)
                            {
                                ArrayList arListAllGXTask3 = new ArrayList();
                                string httpRes3 = "";
                                ArrayList arListRoadMap3 = JTDelayHelper.Instance.getRoadMap(zcFirstBean.wayBillNo, out httpRes3, arListAllGXTask3);
                                dtLastQueryJms = System.DateTime.Now;
                            }
                            System.Threading.Thread.Sleep(200);
                            continue;
                        }
                    }
                    else
                    {
                        while (System.DateTime.Now.Minute != dtExcute.Minute)
                        {
                            if (System.DateTime.Now.Minute == dtExcute.Minute && System.DateTime.Now.Hour == dtExcute.Hour)
                            {
                                break;
                            }
                            TimeSpan ts = System.DateTime.Now - dtLastQueryJms;
                            if (ts.TotalMinutes > 3)
                            {
                                ArrayList arListAllGXTask3 = new ArrayList();
                                string httpRes3 = "";
                                ArrayList arListRoadMap3 = JTDelayHelper.Instance.getRoadMap(zcFirstBean.wayBillNo, out httpRes3, arListAllGXTask3);
                                dtLastQueryJms = System.DateTime.Now;
                            }
                            System.Threading.Thread.Sleep(200);
                            continue;
                        }
                    }

                }

                Hashtable htTotalFailResult = new Hashtable();
                ArrayList arListFailed = new ArrayList();
                Hashtable htCurCount = new Hashtable();

                DateTime dtLastZC = System.DateTime.Now.AddSeconds(-15);
                bool isCurBarcodeValid = true;
                ArrayList arListAppliedTmp = new ArrayList();
                int curIndex = 0;
                ArrayList art = (ArrayList)arListBarcodes;
                int arTotal = art.Count;
                foreach (ZcBean zcBean in (ArrayList)arListBarcodes)
                {

                    totalQueryCount++;
                    StoParams.Instance.resMsg = "";
                    intProcess++;
                    curIndex++;
                    if (arListAppliedTmp.Contains(zcBean.wayBillNo))
                    {
                        continue;
                    }

                    ArrayList arListAllGXTask = new ArrayList();
                    string pickName = "";
                    string orderSource = "";
                    string curSiteToken = "";
                    string customerName = "";
                    if (!isAutoUploadZC)
                    {
                        if (!UtilityHelp.Instance.resetToken(zcBean.wayBillNo, out pickName, out orderSource, out curSiteToken, out customerName))
                        {
                            if (curSiteToken == "")
                            {
                                StoParams.Instance.resMsg = " 发件网点 " + pickName + " 非我司单号  无法处理";
                                zhongcaiEvent.Invoke();
                                StoParams.Instance.htResWechat[zcBean.wayBillNo] = " 发件网点 " + pickName + " 非我司单号  无法处理";
                                arListZCResult.Add(zcBean.wayBillNo + " 发件网点 " + pickName + " 非我司单号  无法处理");
                                continue;
                            }
                            StoParams.Instance.resMsg = " 发件网点 " + pickName + " 非我司单号  无法处理";
                            zhongcaiEvent.Invoke();
                            StoParams.Instance.htResWechat[zcBean.wayBillNo] = " 发件网点 " + pickName + " 非我司单号  无法处理";
                            arListZCResult.Add(zcBean.wayBillNo + " 发件网点 " + pickName + " 非我司单号  无法处理");
                            continue;
                        }
                    }

                    //getCommonWay(zcBean);
                    //getGoodsDetail(zcBean);
                    getSitesName(zcBean);
                    getSecondDelayType(zcBean);
                    getThirdDelayType(zcBean);
                    string outMsg = "";

                    if (zcBean.isSuspend == "1")
                    {
                        outMsg = " 结果: " + "网点异常";
                        arListZCResult.Add(zcBean.wayBillNo + outMsg);
                        StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                        zhongcaiEvent.Invoke();
                        continue;
                    }

                    if (zcBean.isFindThird == false)
                    {
                        outMsg = " 结果: " + "未找到三级类型"+ zcBean.thirdType;
                        arListZCResult.Add(zcBean.wayBillNo + outMsg);
                        StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                        zhongcaiEvent.Invoke();
                        continue;
                    }
                    if (zcBean.goodsName == "")
                    {
                        outMsg = " 结果: " + "未查到商品";
                        arListZCResult.Add(zcBean.wayBillNo + outMsg);
                        StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                        zhongcaiEvent.Invoke();
                        continue;
                    }
                    if (zcBean.secondTypeId == "")
                    {
                        outMsg = " 结果: " + "未查到延误类型";
                        arListZCResult.Add(zcBean.wayBillNo + outMsg);
                        StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                        zhongcaiEvent.Invoke();
                        continue;
                    }
                    TimeSpan tsCur = System.DateTime.Now - dtLastZC;
                    int miniSleep = 0;
                    int maxSleep = 0;
                    getSecondsBySpped(StoParams.Instance.miniSpeed, out miniSleep);
                    getSecondsBySpped(StoParams.Instance.maxSpeed, out maxSleep);
                    Random rdSl = new Random();

                    int sleepTimeMandom = rdSl.Next(maxSleep, miniSleep);

                    int randomSeconds = sleepTimeMandom;
                    //while (tsCur.TotalSeconds<15)
                    if (randomSeconds <= 15)
                    {
                        randomSeconds = 16;
                    }
                    arListAppliedTmp.Clear();
                    while (tsCur.TotalSeconds < randomSeconds)
                    {
                        JArray wayBills = new JArray();

                        for (int curRow = curIndex; curRow < arTotal; curRow++)
                        {
                            ZcBean zc = art[curRow] as ZcBean;
                            wayBills.Add(zc.wayBillNo);
                            break;
                        }

                        arListAppliedTmp = getcurPageApplyed(wayBills);
                        if (arListAppliedTmp.Count > 0)
                        {
                            LogHelper.Instance.writeLog(zcBean.wayBillNo + " 已被别人提交 ");
                            break;
                        }

                        Thread.Sleep(100);
                        tsCur = System.DateTime.Now - dtLastZC;
                    }
                    if (arListAppliedTmp.Count > 0)
                    {
                        continue;
                    }

                    addZhongCai(zcBean, out outMsg);
                    dtLastZC = System.DateTime.Now;
                    LogHelper.Instance.writeLog(zcBean.wayBillNo + " 提交仲裁结果 " + outMsg);
                    string curMinute = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                    /*if (!htCurCount.ContainsKey(curMinute))
                    {
                        htCurCount[curMinute] = 1;
                    }
                    else
                    {
                        int curCout = Convert.ToInt32(htCurCount[curMinute].ToString()) + 1;
                        htCurCount[curMinute] = curCout;
                        if (curCout >= 3)
                        {

                            while (true)
                            {
                                if (System.DateTime.Now.ToString("yyyy-MM-dd HH:mm") != curMinute)
                                {
                                    break;
                                }
                                Thread.Sleep(300);
                            }

                        }
                    }*/

                    if (outMsg.Contains("发生异常"))
                    {
                        htTotalFailResult[zcBean.wayBillNo] = zcBean;
                        arListFailed.Add(zcBean.wayBillNo);
                        /*while (true)
                        {
                            if (System.DateTime.Now.ToString("yyyy-MM-dd HH:mm") != curMinute)
                            {
                                break;
                            }
                            Thread.Sleep(300);
                        }*/
                    }
                    else
                    {
                        arListZCResult.Add(zcBean.wayBillNo + " 结果: " + outMsg);
                        StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                        zhongcaiEvent.Invoke();
                        FrameDecoderManager.Instance.lastSendRes = System.DateTime.Now;
                        Random rd2 = new Random();
                        int miniSecons = 3000;
                        int maxSeconds = 8000;
                        getMillSeconds(curSpeed, out miniSecons, out maxSeconds);
                        int sleepTime2 = rd2.Next(miniSecons, maxSeconds);
                        DateTime dtNow = System.DateTime.Now;
                        int second = dtNow.Second;
                        if (second > 50)
                        {
                            sleepTime2 = 60 * 1000 - second * 1000;
                        }
                        System.Threading.Thread.Sleep(1000);
                        //int sleepTime2 = rd2.Next(8000, 12000);
                        //System.Threading.Thread.Sleep(sleepTime2);
                        //int sleepTime2 = rd2.Next(1500, 3500);
                        if (isAutoUploadZC)
                        {
                            continue;
                        }

                        string newMinute = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm");
                        if (!htCurCount.ContainsKey(newMinute))
                        {
                            continue;
                        }
                        if (curSpeed < 100)
                        {
                            //System.Threading.Thread.Sleep(sleepTime2);
                        }
                    }


                    //Thread.Sleep(1700);
                    //Thread.Sleep(300);


                }

                foreach (string strWaybill in arListFailed)
                {
                    System.Threading.Thread.Sleep(15000);
                    if (htTotalFailResult.ContainsKey(strWaybill))
                    {
                        ZcBean zcBean = htTotalFailResult[strWaybill] as ZcBean;
                        getCommonWay(zcBean);
                        getGoodsDetail(zcBean);
                        getSitesName(zcBean);
                        getSecondDelayType(zcBean);
                        string outMsg = "";

                        if (zcBean.isSuspend == "1")
                        {
                            outMsg = " 结果: " + "网点异常";
                            arListZCResult.Add(zcBean.wayBillNo + outMsg);
                            StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                            zhongcaiEvent.Invoke();
                            continue;
                        }
                        if (zcBean.goodsName == "")
                        {
                            outMsg = " 结果: " + "未查到商品";
                            arListZCResult.Add(zcBean.wayBillNo + outMsg);
                            StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                            zhongcaiEvent.Invoke();
                            continue;
                        }
                        if (zcBean.secondTypeId == "")
                        {
                            outMsg = " 结果: " + "未查到延误类型";
                            arListZCResult.Add(zcBean.wayBillNo + outMsg);
                            StoParams.Instance.resMsg = zcBean.wayBillNo + " " + outMsg;
                            zhongcaiEvent.Invoke();
                            continue;
                        }

                        addZhongCai(zcBean, out outMsg);

                        arListZCResult.Add(zcBean.wayBillNo + " 结果: " + outMsg);
                    }


                }

                string dir = System.Environment.CurrentDirectory;
                string date = System.DateTime.Now.Date.ToShortDateString();
                string path = StoParams.Instance.outputDir + "\\" + date + "批量仲裁结果.txt";
                swb = new StreamWriter(path, true);
                int sucessCount = 0;
                foreach (string strLine in arListZCResult)
                {
                    if (strLine.Contains("成功"))
                    {
                        sucessCount++;
                    }
                    swb.WriteLine(strLine);
                }
                swb.Close();
                System.Windows.Forms.MessageBox.Show("批量仲裁提交完成，总计导入：" + totalQueryCount.ToString() + "条 提交成功:" + sucessCount.ToString() + "条\r\n 详情见结果文件:" + path);



            }
            catch (Exception ex)
            {


            }
            int tiot = queryServerResTime;



        }



        private void initLog()
        {
            try
            {
                string dir = System.Environment.CurrentDirectory;
                bFile = new FileStream(dir + "\\error.txt", FileMode.Create);
                if (swb == null)
                {
                    swb = new StreamWriter(bFile);
                    swb.WriteLine("begin");

                }
            }
            catch (Exception ex)
            {

            }

        }


    }
}
